// const HTTP_BASE_URL = 'http://x2899ad4.natappfree.cc';
import {subscribeMessageJK, subscribeMessageSK} from "@/utils/huida";

// const HTTP_BASE_URL = 'http://zea6b2c9.natappfree.cc';
// const SOCKET_URL = 'ws://127.0.0.1:1010/connect';
// const SOCKET_URL = 'ws://p2697645.natappfree.cc/connect';
// const HTTP_BASE_URL = 'https://prod.guiniao.online/api';
// const SOCKET_URL = 'wss://prod.guiniao.online/socket/connect';
// const SOCKET_URL = 'wss://y8d6f994.natappfree.cc/connect';
const HTTP_BASE_URL = 'https://www.hdkj.cloud/api';
const SOCKET_URL = 'wss://www.hdkj.cloud:1010/socket/connect';

// 结算到款通知模板id
const jkTemplateId = "YcB0VfQ6KWMNlB8ZgdEhekfzG_q46l4Bio7UpHFy7iQ"
// 收款成功通知模板id
const skTemplateId = "J5QFylBPU9YGflfZNq9R4q4Q0VRzvIHnEhZQI-0aO-I"

const $hd = {
	mapKey: 'FTMBZ-3L56Z-BSOXA-ZPLHK-OGBW2-LBFZD',
	baseUrl: HTTP_BASE_URL,
	/**
	 * 校验是否登录，需配合 await 使用
	 * 校验通过返回用户信息，失败返回 false
	 *
	 * @returns {Promise<boolean>}
	 */
	isLogin: async () => {
		const res = await uni.$uv.http.get(`/${uni.getStorageSync("login-type")}/info`, {
			custom: {
				toast: false
			}
		})
		return res && res.code === 200 ? res.user : false
	},
	// 获取登录角色：fs=飞手；farmer=农户
	loginRole: () => uni.getStorageSync("login-type"),
	// 经纬度信息
	position: null,
	socket: {
		isConnect: false,
	},
	sysConfig: async () => {
		try {
			const res = await uni.$uv.http.get(`/system/config/map`, {
				custom: {
					toast: false,
					token: false
				}
			})
			return res && res.code === 200 ? res.data : {}
		} catch (_) {
			return {}
		}
	},
	// 调起客户端小程序【结算到款通知】订阅消息界面
	subscribeMessageJK: () => {
		uni.requestSubscribeMessage({
			//培训学习通知和活动审核通知
			tmplIds: [jkTemplateId],
			complete(res) {
				console.log("订阅模板消息的回调")
				console.log(res)
			}
		})
	},
	// 调起客户端小程序【收款成功通知】订阅消息界面
	subscribeMessageSK: () => {
		uni.requestSubscribeMessage({
			//培训学习通知和活动审核通知
			tmplIds: [skTemplateId],
			complete(res) {
				console.log("订阅模板消息的回调")
				console.log(res)
			}
		})
	}
}
uni.$hd = $hd;

const install = (Vue, options = {}) => {
	Vue.mixin({
		data() {
			return {
				$hd: $hd,
			}
		},
		async onShow() {
			this.$hd = $hd;

			if (await this.$hd.isLogin()) {
				this.initScokets()
			}
		},
		methods: {
			initScokets() {
				console.log(this.$hd.socket.isConnect)
				if (this.$hd.socket.isConnect || !uni.getStorageSync('token')) return
				if (this.$hd.socket.interval)
					clearInterval(this.$hd.socket.interval);
				uni.connectSocket({
					// 测试地址 根据自身填写
					url: SOCKET_URL,
					success: (res) => {
						this.connectSocket(); //1、判断是否打开连接
						this.socketMessage(); //2、判断websocket服务器是否返回信息
					},
					fail: (err) => {
						this.$hd.socket.isConnect = false
						console.log("***** WebSocket连接失败 connectSocket= *****", err);
						uni.onSocketError((res) => {
							uni.$off("socketMessage")
							this.initScokets(); //连接失败之后，重新向服务器发起连接
						});
					},
				});
			},
			connectSocket() {
				console.log("WebSocket连接成功....");
				this.$hd.socket.isConnect = true
				uni.onSocketOpen((res) => {
					console.log('WebSocket连接已打开！',res)
					uni.sendSocketMessage({
						data: JSON.stringify({
							type: "mobile",
							token: uni.getStorageSync('token') || ''
						}),
					});
					this.resetSocket(); //连接成功之后做两秒的一次连接(心跳机制)
				});
			},
			resetSocket() {
				// return
				this.$hd.socket.interval = setInterval(() => {
					//做一个判断：在没有获取某个值货值其他需求下，做个无响应的websocket连接。否则就                 做一个有响应的连接
					uni.sendSocketMessage({
						data: JSON.stringify({
							type: "mobile",
							token: uni.getStorageSync('token') || ''
						}),
						success: (res) => {
							this.$hd.socket.isConnect = true
						},
						fail: (err) => {
							console.log("***** webSocket心跳维持失败,重新连接.... *****");
							uni.$off("socketMessage")
							this.$hd.socket.isConnect = false
							this.initScokets();
						},
					});
				}, 3000);
			},
			socketMessage() {
				uni.onSocketMessage((res) => {
					//获取服务器返回内容，并获取当前时间戳以作服务器超时判断
					try {
						let data = JSON.parse(res.data);
						if (data.type) {
							//客服消息
							let msg = {
								content: data.content,
								lastMessageTime: data.createDate,
							}
							this.$store.commit("message/add_customer_count");
							this.$store.commit("message/update_customer", msg);
							this.$store.commit("message/update_tabs");
							uni.$emit("socketMessage", data);
						} else {
							//消息中心
							uni.$emit("orderMessage", data);
							this.$store.dispatch("message/updateMessage");
						}

					} catch (e) {}
				});
			}
		}
	})
	// #ifndef APP-NVUE
	Vue.prototype.$hd = $hd;
	// #endif
}

export default {
	install
};
